package com.donger.business.upms.handler.login;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.donger.business.upms.enums.LoginTypeEnum;
import com.donger.business.upms.entity.SysSocialDetails;
import com.donger.business.upms.entity.SysUser;
import com.donger.business.upms.mapper.SysSocialDetailsMapper;
import com.donger.business.upms.service.ISysUserService;
import com.donger.common.core.constant.SecurityConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author 7326
 */
@Component("GITEE")
@AllArgsConstructor
@Slf4j
public class GiteeLoginHandler extends AbstractLoginHandler {
    private final SysSocialDetailsMapper sysSocialDetailsMapper;
    private final ISysUserService sysUserService;


    @Override
    public String identify(String code) {
        SysSocialDetails condition = new SysSocialDetails();
        condition.setType(LoginTypeEnum.GITEE.getType());

        SysSocialDetails socialDetails = sysSocialDetailsMapper.selectOne(new QueryWrapper<>(condition));


        String url = String.format(SecurityConstants.GITEE_AUTHORIZATION_CODE_URL, code
                , socialDetails.getAppId(), URLUtil.encode(socialDetails.getRedirectUrl()), socialDetails.getAppSecret());
        String result = HttpUtil.post(url, new HashMap<>(0));
        log.debug("码云响应报文:{}", result);

        String accessToken = JSONUtil.parseObj(result).getStr("access_token");
        String userUrl = String.format(SecurityConstants.GITEE_USER_INFO_URL, accessToken);
        String resp = HttpUtil.get(userUrl);
        log.debug("码云获取个人信息返回报文{}", resp);

        JSONObject userInfo = JSONUtil.parseObj(resp);
        //码云唯一标识
        return userInfo.getStr("login");
    }

    @Override
    public SysUser info(String identify) {

        SysUser user = sysUserService
                .getOne(Wrappers.<SysUser>query()
                        .lambda().eq(SysUser::getGiteeLogin, identify));

        if (user == null) {
            log.info("码云未绑定:{}", identify);
            return null;
        }
        return user;
    }
}
